<template>
  <el-table ref="dragTable" :data="newtableData" style="width: 100%">
    <el-table-column prop="date" label="日期" width="180"></el-table-column>
    <el-table-column prop="name" label="姓名" width="180"></el-table-column>
    <el-table-column prop="address" label="地址"></el-table-column>
  </el-table>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  props: {
    tableData: {
      type: Array,
      default: () => []
    }
  },
  // computed: {
  //   newtableData () {
  //     return [...this.tableData]
  //   }
  // },
  data () {
    const _ = require('lodash')

    return {
      // newtableData: JSON.parse(JSON.stringify(this.tableData)),
      // newtableData: this.tableData.map(el => { return { ...el } }),
      newtableData: _.cloneDeep(this.tableData),
      oldList: this.tableData,
      newList: [],
      sortable: null
    }
  },
  created () {
    // console.log(this.newtableData)

    this.$nextTick(() => {
      this.setSort()
    })
  },
  methods: {
    setSort () {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          // console.log(this.newtableData)
          const targetRow = this.newtableData.splice(evt.oldIndex, 1)[0]
          console.log(this.newtableData.splice(evt.oldIndex, 1))
          this.newtableData.splice(evt.newIndex, 0, targetRow)

          // // console.log(this.tableData[0].address)
          // console.log(this.newtableData[0].address)
          // // for show the changes, you can delete in you code
          // const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          // this.newList.splice(evt.newIndex, 0, tempIndex)
          // console.log(this.newtableData)
        }
      })
    }
  }

}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>
